package com.oa.erp.pur.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.audit.log.client.annotation.AuditLog;
import com.mdp.audit.log.client.annotation.OperType;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.query.QueryTools;
import com.mdp.core.utils.RequestUtils;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.oa.erp.pur.entity.StockIn;
import com.oa.erp.pur.entity.StockInDetail;
import com.oa.erp.pur.service.StockInService;
import com.oa.erp.pur.vo.StockInAddVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月8日
 */
@RestController
@RequestMapping(value = "/*/oa/erp/pur/stockIn")
@Api(tags = {"pur_stock_in-操作接口"})
public class StockInController {

    static Logger logger = LoggerFactory.getLogger(StockInController.class);

    @Autowired
    private StockInService stockInService;

    @ApiOperation(value = "pur_stock_in-查询列表", notes = " ")
    @ApiEntityParams(StockIn.class)
    @ApiResponses({@ApiResponse(code = 200, response = StockIn.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result listStockIn(@ApiIgnore @RequestParam Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        RequestUtils.transformArray(params, "ids");
        QueryWrapper<StockIn> qw = QueryTools.initQueryWrapper(StockIn.class, params);
        IPage page = QueryTools.initPage(params);
        List<Map<String, Object>> stockInList = stockInService.selectListMapByWhere(page, qw, params);

        return Result.ok("query-ok", "查询成功").setData(stockInList).setTotal(page.getTotal());
    }


    @ApiOperation(value = "pur_stock_in-新增", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = StockIn.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addStockIn(@RequestBody StockInAddVo stockInAddVo) {


        if (StringUtils.isEmpty(stockInAddVo.getStockIn().getId())) {
            stockInAddVo.getStockIn().setId(stockInService.createKey("id"));
        } else {
            StockIn stockInQuery = new StockIn(stockInAddVo.getStockIn().getId());
            if (stockInService.countByWhere(stockInQuery) > 0) {
                return Result.error("编号重复，请修改编号再提交");
            }
        }
        if (stockInAddVo.getStockInDetails() == null || stockInAddVo.getStockInDetails().size() == 0) {
            return Result.error("stockInDetails-0", "入库明细数据为空");
        }
        List<StockInDetail> stockInDetails = stockInAddVo.getStockInDetails();
        if (stockInDetails.stream().filter(i -> !StringUtils.hasText(i.getAssetSn())).findAny().isPresent()) {
            return Result.error("assetSn-0", "资产编码不能为空");
        }
        User user = LoginUtils.getCurrentUserInfo();
        BigDecimal inNum = BigDecimal.ZERO;
        stockInAddVo.getStockIn().setReqBranchId(user.getBranchId());
        for (StockInDetail stockInDetail : stockInAddVo.getStockInDetails()) {
            stockInDetail.setBranchId(user.getBranchId());
            stockInDetail.setReceiptNo(stockInAddVo.getStockIn().getId());
            inNum = inNum.add(stockInDetail.getInNum());
        }
        stockInAddVo.getStockIn().setTotalInNum(inNum);
        stockInService.insertStockIn(stockInAddVo);

        return Result.ok("add-ok", "添加成功！").setData(stockInAddVo);
    }

    @ApiOperation(value = "查询pur_stock_in明细信息列表", notes = "listStockIn,条件之间是 and关系,模糊查询写法如 {studentName:'%才哥%'}")
    @ApiResponses({@ApiResponse(code = 200, response = StockIn.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},pageInfo:{total:总记录数},data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/listStorkInDetail", method = RequestMethod.GET)
    public Result listStorkInDetail(@RequestParam String id) {

        Map<String, Object> m = new HashMap<>();
        Map<String, Object> stockInList = stockInService.listStorkInDetail(id);    //列出StockIn列表
        return Result.ok("", "查询成功").setData(stockInList);
    }


    @ApiOperation(value = "查询入库表通过Id", notes = "listStockIn,条件之间是 and关系,模糊查询写法如 {studentName:'%才哥%'}")
    @ApiResponses({@ApiResponse(code = 200, response = StockIn.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},pageInfo:{total:总记录数},data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/getStockInById", method = RequestMethod.GET)
    public Result getStockInById(@RequestParam String id) {
        StockIn stockIn = new StockIn();
        stockIn.setId(id);
        StockIn result = stockInService.selectOneObject(stockIn);

        return Result.ok("", "查询成功").setData(result);
    }

    @ApiOperation(value = "pur_stock_in-删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delStockIn(@RequestBody StockIn stockIn) {


        stockInService.delStockIn(stockIn);

        return Result.ok("del-ok", "删除成功！");
    }

    @ApiOperation(value = "pur_stock_in-修改", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = StockIn.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result editStockIn(@RequestBody StockInAddVo stockInAddVo) {

        List<StockInDetail> stockInDetails = stockInAddVo.getStockInDetails();
        if (stockInDetails == null || stockInDetails.size() == 0) {
            return Result.error("stockInDetails-0", "明细数据不能为空");
        }
        if (stockInDetails.stream().filter(i -> !StringUtils.hasText(i.getAssetSn())).findAny().isPresent()) {
            return Result.error("assetSn-0", "资产编码不能为空");
        }
        User user = LoginUtils.getCurrentUserInfo();
        stockInAddVo.getStockIn().setReqBranchId(user.getBranchId());
        BigDecimal inNum = BigDecimal.ZERO;
        for (StockInDetail stockInDetail : stockInAddVo.getStockInDetails()) {
            stockInDetail.setBranchId(user.getBranchId());
            stockInDetail.setReceiptNo(stockInAddVo.getStockIn().getId());
            inNum = inNum.add(stockInDetail.getInNum());
        }
        stockInAddVo.getStockIn().setTotalInNum(inNum);
        stockInService.updateStockIn(stockInAddVo);

        return Result.ok("del-ok", "更新成功！").setData(stockInAddVo);
    }

    @ApiOperation(value = "pur_stock_in-批量修改某些字段", notes = "")
    @ApiEntityParams(value = StockIn.class, props = {}, remark = "pur_stock_in", paramType = "body")
    @ApiResponses({@ApiResponse(code = 200, response = StockIn.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/editSomeFields", method = RequestMethod.POST)
    public Result editSomeFields(@ApiIgnore @RequestBody Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        stockInService.editSomeFields(params);
        return Result.ok("edit-ok", "更新成功");
    }

    @ApiOperation(value = "pur_stock_in-批量删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public Result batchDelStockIn(@RequestBody List<StockIn> stockIns) {
        User user = LoginUtils.getCurrentUserInfo();
        if (stockIns.size() <= 0) {
            return Result.error("batchDel-data-err-0", "请上送待删除数据列表");
        }
        List<StockIn> datasDb = stockInService.listByIds(stockIns.stream().map(i -> i.getId()).collect(Collectors.toList()));

        List<StockIn> can = new ArrayList<>();
        List<StockIn> no = new ArrayList<>();
        for (StockIn data : datasDb) {
            if (true) {
                can.add(data);
            } else {
                no.add(data);
            }
        }
        List<String> msgs = new ArrayList<>();
        if (can.size() > 0) {
            stockInService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num", "成功删除%s条数据.", can.size()));
        }

        if (no.size() > 0) {
            msgs.add(LangTips.transMsg("not-allow-del-num", "以下%s条数据不能删除:【%s】", no.size(), no.stream().map(i -> i.getId()).collect(Collectors.joining(","))));
        }
        if (can.size() > 0) {
            return Result.ok(msgs.stream().collect(Collectors.joining()));
        } else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
    }

    @ApiOperation(value = "pur_stock_in-根据主键查询一条数据", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = StockIn.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result queryById(StockIn stockIn) {
        StockIn data = (StockIn) stockInService.getById(stockIn);
        return Result.ok().setData(data);
    }

    //入库单审批流
    @AuditLog(firstMenu = "资产管理", secondMenu = "资产入库", func = "processApprova", funcDesc = "资产入库流程", operType = OperType.UPDATE)
    @RequestMapping(value = "/processApprova", method = RequestMethod.POST)
    public Result processApprova(@RequestBody Map<String, Object> flowVars) {
        QueryWrapper<StockIn> qw = QueryTools.initQueryWrapper(StockIn.class, flowVars);
        IPage page = QueryTools.initPage(flowVars);


        this.stockInService.processApprova(page, qw, flowVars);
        logger.debug("procInstId=====" + flowVars.get("procInstId"));

        return Result.ok("", "成功提交审批").setTotal(page.getTotal());
    }

}
